<template>
  <div style="position: relative">
    <div ref="basicDataPie" style="width: 500px; height: 300px"></div>
    <div class="legends">
      <div v-for="(item, index) in chartData" :key="index" class="legend-item">
        <div class="legend-name">
          <div
            class="legend-color"
            :style="{ background: item?.itemStyle?.color }"
          ></div>
          {{ item.name }}
        </div>
        <div class="legend-value common-num">{{ item.value }}%</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from "vue";
import * as echarts from "echarts";
import "echarts-gl";

// 图表数据
const chartData = ref([]);
const basicDataPie = ref(null);

// 模拟接口调用
const fetchData = async () => {
  try {
    // 这里模拟异步请求
    const mockData = [
      { name: "1号线", value: 70, itemStyle: { color: "#3EA5F0" } },
      { name: "2号线", value: 6, itemStyle: { color: "#D24BD7" } },
      { name: "3号线", value: 4, itemStyle: { color: "#83EA7F" } },
      { name: "4号线", value: 3, itemStyle: { color: "#8578FF" } },
      { name: "5号线", value: 1, itemStyle: { color: "#FFA858" } },
      { name: "6号线", value: 2, itemStyle: { color: "#00E0DB" } },
      { name: "9号线", value: 2, itemStyle: { color: "#DE9F58" } },
      { name: "10号线", value: 1, itemStyle: { color: "#DEBB58" } },
      { name: "12号线", value: 6, itemStyle: { color: "#A4E1FF" } },
      { name: "18号线", value: 2, itemStyle: { color: "#594BD7" } },
      { name: "环线", value: 4, itemStyle: { color: "#FAEF4A" } },
      { name: "国博线", value: 4, itemStyle: { color: "#9B95F5" } },
      { name: "江跳线", value: 5, itemStyle: { color: "#D24BD7" } },
    ];

    // 模拟接口延迟
    await new Promise((resolve) => setTimeout(resolve, 10));
    chartData.value = mockData;
    nextTick(() => {
      echartsPie();
    });
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

const echartsPie = () => {
  let hoveredIndex = "";
  let chartDom = basicDataPie.value;
  let myChart = echarts.init(chartDom);

  const getPie3D = (pieData) => {
    let series = [];
    let sumValue = 0;
    let startValue = 0;
    let endValue = 0;
    let k = 1;
    pieData.sort((a, b) => b.value - a.value);

    // 为每一个饼图数据，生成一个 series-surface 配置
    for (let i = 0; i < pieData.length; i++) {
      sumValue += pieData[i].value;
      let seriesItem = {
        name:
          typeof pieData[i].name === "undefined"
            ? `series${i}`
            : pieData[i].name,
        type: "surface",
        parametric: true,
        wireframe: { show: false },
        pieData: pieData[i],
        pieStatus: { selected: false, hovered: false, k: k },
        radius: "50%",
        center: ["10%", "10%"],
      };

      if (typeof pieData[i].itemStyle != "undefined") {
        let itemStyle = {
          color: pieData[i].itemStyle.color,
          opacity: 1,
        };
        seriesItem.itemStyle = itemStyle;
      }
      series.push(seriesItem);
    }

    // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
    // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
    for (let i = 0; i < series.length; i++) {
      endValue = startValue + series[i].pieData.value;
      series[i].pieData.startRatio = startValue / sumValue;
      series[i].pieData.endRatio = endValue / sumValue;
      series[i].parametricEquation = getParametricEquation(
        series[i].pieData.startRatio,
        series[i].pieData.endRatio,
        false,
        false,
        k,
        series[i].pieData.value
      );
      startValue = endValue;
    }

    let boxHeight = getHeight3D(series, 40); //通过传参设定3d饼/环的高度，26代表26px
    // 准备待返回的配置项，把准备好的 legendData、series 传入。
    let option = {
      backgroundColor: "transparent",
      tooltip: {
        backgroundColor: "#fff",
        formatter: (params) => {
          if (
            params.seriesName !== "mouseoutSeries" &&
            params.seriesName !== "pie3d"
          ) {
            let bfb = (
              (option.series[params.seriesIndex].pieData.endRatio -
                option.series[params.seriesIndex].pieData.startRatio) *
              100
            ).toFixed(2);
            return (
              `${params.seriesName}<br/>` +
              `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>` +
              `${bfb}%`
            );
          }
        },
      },
      xAxis3D: { min: -1, max: 1 },
      yAxis3D: { min: -1, max: 1 },
      zAxis3D: { min: -1, max: 1 },
      grid3D: {
        show: false,
        boxHeight: boxHeight,
        left: -50,
        top: -50,
        viewControl: {
          alpha: 25,
          distance: 350,
          rotateSensitivity: 0,
          zoomSensitivity: 0,
          panSensitivity: 0,
          autoRotate: false,
        },
        light: {
          main: {
            intensity: 1.5,
            alpha: 20,
            shadow: false,
          },
          ambient: {
            intensity: 1,
          },
          ambientCubemap: {
            texture: null,
            diffuseIntensity: 1,
            specularIntensity: 1,
          },
        },
        environment: "none",
        postEffect: {
          enable: true,
          bloom: {
            enable: true,
            intensity: 0.1,
          },
          SSAO: {
            enable: false,
          },
        },
        temporalSuperSampling: {
          enable: true,
        },
      },
      series: series,
    };
    return option;
  };

  //获取3d丙图的最高扇区的高度
  const getHeight3D = (series, height) => {
    series.sort((a, b) => b.pieData.value - a.pieData.value);
    return (height * 15) / series[0].pieData.value;
  };

  // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
  const getParametricEquation = (
    startRatio,
    endRatio,
    isSelected,
    isHovered,
    k,
    h
  ) => {
    // 计算
    let midRatio = (startRatio + endRatio) / 2;
    let startRadian = startRatio * Math.PI * 2;
    let endRadian = endRatio * Math.PI * 2;
    let midRadian = midRatio * Math.PI * 2;
    // 如果只有一个扇形，则不实现选中效果。
    if (startRatio === 0 && endRatio === 1) {
      isSelected = false;
    }
    // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
    k = typeof k !== "undefined" ? k : 1 / 3;
    // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
    let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
    let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
    // 计算高亮效果的放大比例（未高亮，则比例为 1）
    let hoverRate = isHovered ? 1.05 : 1;
    // 返回曲面参数方程
    return {
      u: { min: -Math.PI, max: Math.PI * 3, step: Math.PI / 32 },
      v: { min: 0, max: Math.PI * 2, step: Math.PI / 20 },
      x: function (u, v) {
        if (u < startRadian) {
          return (
            offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        if (u > endRadian) {
          return (
            offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
      },
      y: function (u, v) {
        if (u < startRadian) {
          return (
            offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        if (u > endRadian) {
          return (
            offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
      },
      z: function (u, v) {
        if (u < -Math.PI * 0.5) {
          return Math.sin(u);
        }
        if (u > Math.PI * 2.5) {
          return Math.sin(u) * h * 0.1;
        }
        return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;
      },
    };
  };

  let option = getPie3D(chartData.value, 0.8);

  // 添加透明的2d饼图用于label指引线
  option.series.push({
    type: "pie",
    label: { show: false, position: "inside", formatter: "{c}%" },
    radius: ["65%", "65%"],
    center: ["55%", "48%"],
    itemStyle: { opacity: 0 },
  });

  option && myChart.setOption(option);

  myChart.on("mouseover", function (params) {
    // 准备重新渲染扇形所需的参数
    let isSelected;
    let isHovered;
    let startRatio;
    let endRatio;
    let k;
    let i;

    // 如果触发 mouseover 的扇形当前已高亮，则不做操作
    if (hoveredIndex === params.seriesIndex) {
      return void 0;
      // 否则进行高亮及必要的取消高亮操作
    } else {
      // 如果当前有高亮的扇形，取消其高亮状态（对 option 更新）
      if (hoveredIndex !== "") {
        // 从 option.series 中读取重新渲染扇形所需的参数，将是否高亮设置为 false。
        isSelected = option.series[hoveredIndex].pieStatus.selected;
        isHovered = false;
        startRatio = option.series[hoveredIndex].pieData.startRatio;
        endRatio = option.series[hoveredIndex].pieData.endRatio;
        k = option.series[hoveredIndex].pieStatus.k;
        i =
          option.series[hoveredIndex].pieData.value ===
          option.series[0].pieData.value
            ? 35
            : 10;
        // 对当前点击的扇形，执行取消高亮操作（对 option 更新）
        option.series[hoveredIndex].parametricEquation = getParametricEquation(
          startRatio,
          endRatio,
          isSelected,
          isHovered,
          k,
          i
        );
        option.series[hoveredIndex].pieStatus.hovered = isHovered;

        // 将此前记录的上次选中的扇形对应的系列号 seriesIndex 清空
        hoveredIndex = "";
      }

      // 如果触发 mouseover 的扇形不是透明圆环，将其高亮（对 option 更新）
      if (
        params.seriesName !== "mouseoutSeries" &&
        option.series[params.seriesIndex].pieStatus
      ) {
        // 从 option.series 中读取重新渲染扇形所需的参数，将是否高亮设置为 true。
        isSelected = option.series[params.seriesIndex].pieStatus.selected;
        isHovered = true;
        startRatio = option.series[params.seriesIndex].pieData.startRatio;
        endRatio = option.series[params.seriesIndex].pieData.endRatio;
        k = option.series[params.seriesIndex].pieStatus.k;

        // 对当前点击的扇形，执行高亮操作（对 option 更新）
        option.series[params.seriesIndex].parametricEquation =
          getParametricEquation(
            startRatio,
            endRatio,
            isSelected,
            isHovered,
            k,
            option.series[params.seriesIndex].pieData.value + 5
          );
        option.series[params.seriesIndex].pieStatus.hovered = isHovered;

        // 记录上次高亮的扇形对应的系列号 seriesIndex
        hoveredIndex = params.seriesIndex;
      }

      // 使用更新后的 option，渲染图表
      myChart.setOption(option);
    }
  });
};

onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.legends {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 250px;
  height: 100px;
  flex-wrap: wrap;
  left: 30px;
  bottom: 50px;

  .legend-item {
    margin-top: 5px;
    display: flex;
    width: 70px;
    margin-right: 10px;
    font-size: 12px;
    justify-content: space-between;
    align-items: center;

    .legend-color {
      width: 6px;
      height: 6px;
      display: inline-block;
      border-radius: 50%;
      margin-right: 3px;
    }

    .legend-name {
      color: rgba(255, 255, 255, 0.8);
    }

    .legend-value {
      color: #deedff;
    }
  }
}
</style>
